package com.youlin.untils;

import com.youlin.security.SecurityUser;
import com.youlin.entities.BygAdmin;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import java.util.List;

public class AdminUtil {

    private AdminUtil() {
        throw new IllegalStateException("Utility class");
    }

    public static SecurityUser getSecurityUser () {
        return (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public static BygAdmin getCurrentAdmin () {
        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return securityUser.bygAdmin;
    }

    public static void setCurrentAdmin (SecurityUser userDetails) {
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities()));
    }

    public static void removeUser (SessionRegistry sessionRegistry, SecurityUser principal) {
        List<SessionInformation> sessionsInfo = sessionRegistry
                .getAllSessions(principal, false); // false代表不包含过期session
        if (MyBeanUtil.isEmpty(sessionsInfo)) return;
        for (SessionInformation sessionInformation : sessionsInfo)
            sessionInformation.expireNow();
    }

    public static void onlyUser (SessionRegistry sessionRegistry, SecurityUser principal, String JSESSIONID) {
        List<SessionInformation> sessionsInfo = sessionRegistry
                .getAllSessions(principal, false); // false代表不包含过期session
        if (MyBeanUtil.isEmpty(sessionsInfo)) return;
        for (SessionInformation sessionInformation : sessionsInfo)
            if (! JSESSIONID.contains(sessionInformation.getSessionId()))
                sessionInformation.expireNow();
    }

    public static boolean findUser (SessionRegistry sessionRegistry, SecurityUser principal, String JSESSIONID) {
        List<SessionInformation> sessions = sessionRegistry
                .getAllSessions(principal, false); // false代表不包含过期session
        return sessions.parallelStream().anyMatch(session -> session.getSessionId().equals(JSESSIONID));
    }

}
